from typing import Optional
from sqlalchemy.orm import Session

from ..crud.base import CRUDBase
from ..models.user import User
from ..schemas.user import UserCreate, UserUpdate
from ..core.security import get_password_hash, verify_password

class CRUDUser(CRUDBase[User, UserCreate, UserUpdate]):
    def get_by_email(self, db: Session, *, email: str) -> Optional[User]:
        """通过邮箱获取用户"""
        return db.query(User).filter(User.email == email).first()

    def get_by_account_id(self, db: Session, *, account_id: str) -> Optional[User]:
        """通过学号获取用户"""
        return db.query(User).filter(User.account_id == account_id).first()

    def get_by_phone_number(self, db: Session, *, phone_number: str) -> Optional[User]:
        """通过手机号获取用户"""
        return db.query(User).filter(User.phone_number == phone_number).first()

    def create(self, db: Session, *, obj_in: UserCreate) -> User:
        """创建新用户"""
        db_obj = User(
            name=obj_in.name,
            email=obj_in.email,
            account_id=obj_in.account_id,
            phone_number=obj_in.phone_number,
            hashed_password=get_password_hash(obj_in.password),
            role=obj_in.role,
            is_active=True
        )
        db.add(db_obj)
        db.commit()
        db.refresh(db_obj)
        return db_obj

    def authenticate(self, db: Session, *, account_id: str, password: str) -> Optional[User]:
        """验证用户"""
        user = self.get_by_account_id(db, account_id=account_id)
        if not user:
            return None
        if not verify_password(password, user.hashed_password):
            return None
        return user

user_crud = CRUDUser(User)